package com.lry.basic.algorithm.common;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/7/12
 */
public class NumOfOne {
    public static void main(String[] args) {
        System.out.println(num(10));
        System.out.println(num1(10));
        System.out.println(num2(10));
        System.out.println(isTwoPower(1024));
        System.out.println(isTwoPower(3));
        System.out.println(howNum(10, 13));
        System.out.println(getInt(getBytes(180)));
    }
    public static int num(int n){
        int count=0;
        while(n>0){
            if((n&1)!=0)++count;
            n>>=1;
        }
        return count;
    }
    public static int num1(int n){
        int count=0;
        int flag = 1;
        while(flag>0){
            if((n&flag)!=0)++count;
            flag<<=1;
        }
        return count;
    }
    public static int num2(int n){
        int count=0;
        while(n>0){
            ++count;
            n = n&(n-1);//会把最右边的1消掉
        }
        return count;
    }
    //是否是2的n次方 n>=0
    public static boolean isTwoPower(int n){
        n = n&(n-1);//会把最右边的1消掉
        return n==0;
    }

    public static int howNum(int m,int n){
        int x = m^n;
        return num2(x);
    }

    public static byte[] getBytes(int n){
        byte[] bytes = new byte[4];
        bytes[0] = (byte) n;
        bytes[1] = (byte) (n>>8);
        bytes[2] = (byte) (n>>16);
        bytes[3] = (byte) (n>>24);
        return bytes;
    }
    public static int getInt(byte[] bytes){
        int int1 = bytes[0]&0xff;
        int int2 = bytes[1]&0xff<<8;
        int int3 = bytes[2]&0xff<<16;
        int int4 = bytes[3]&0xff<<24;
        return int1|int2|int3|int4;
    }
}
